﻿using IntoCommon.Util;
using IntoLog;
using IntoStationSystem.Db;
using IntoStationSystem.Entity;
using IntoStationSystem.Enums;
using IntoStationSystem.Global;
using IntoStationSystem.Models;
using IntoStationSystem.PLC;
using Newtonsoft.Json.Linq;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls.Primitives;
using static IntoStationSystem.Global.Events;

namespace IntoStationSystem.ViewModels
{
    public class HomeViewModel : BindableBase
    {
        public bool HasAlarm = false;
        /// <summary>
        /// plc提示信息，包括报警、警告、提示
        /// </summary>
        public ObservableCollection<Msg> PlcMsgs { get; set; } = new ObservableCollection<Msg>();
        /// <summary>
        /// 产品型号配置
        /// </summary>
        private ProductSettingViewModel proCfg => Locator.Instance.ProductSettingVM;
        /// <summary>
        /// 界面显示的日志
        /// </summary>
        public LogService Log => Locator.Instance.Log;

        //风扇值，泄露值
        public DCFanModel Fan { get; set; } = new DCFanModel();


        public LeakageModel Leakage { get; set; } = new LeakageModel();

        /// <summary>
        /// 主界面数据模型
        /// </summary>
        public HomeModel HomeModel { get; set; } = new HomeModel();
        /// <summary>
        /// 零件码：数量10个
        /// </summary>
        public ObservableCollection<string> PartCodes { get; set; } = new ObservableCollection<string>();
        //扫码完成数量
        public int ScanCompleteNum = 0;
        //允许扫码
        public bool EnablScan = false;

        //public string RepeatCode = string.Empty;

        private string scanCode;
        public string ScanCode
        {
            get => scanCode;
            set
            {
                if (string.IsNullOrEmpty(value)) return;

                scanCode = value.Trim();
                bool isMatch = false;
                //检查扫码是否正确

                if (Fields.Station=="OP40")
                {
                    //获取配方
                    var pros = DbHelper.GetConfig<ProductModel>(ProModel).ToList();
                    if (pros[0].RealValue + pros[1].RealValue + pros[2].RealValue != proCfg.EnableScans.Count)
                    {
                        HandyControl.Controls.MessageBox.Show("配置的零件条码个数与扫码配置的总数不同，请重新配后扫码!");
                        DbHelper.Log("配置的零件条码个数与扫码配置的总数不同，请重新配后扫码!");
                        return;

                    }


                }
                //判断总成码是否重复
                if (Fields.Station == "OP60")
                {
                    ProduceData product2 = null;
                    product2 = DbHelper.GetCodeStationData(scanCode);
                    if (product2 != null)
                    {
                        HandyControl.Controls.MessageBox.Show("总成码重复，请重新打印生成总成码!");
                        return;

                    }
                }

                for (int i = 0; i < proCfg.EnableScans.Count; i++)
                {
                    if (scanCode.Contains(proCfg.EnableScans[i].MatchCode) && proCfg.EnableScans[i].CodeLen == scanCode.Length)
                    {
                        //校验成功后需要检查该零件码是否在数据中已经存在，防止重码,不存在保存数据库
                        
                        if (PartCodes.Count != i)
                        {

                            if (PartCodes.Count > 1 && i >= 1)
                            {
                                
                                    for (int j = i-1; j >=0; j--)
                                    {
                                        if (string.IsNullOrEmpty(PartCodes[j]))
                                        {

                                            HandyControl.Controls.MessageBox.Show("零件条码不符合扫码顺序，请重新扫码!");
                                            DbHelper.Log("零件条码不符合扫码顺序，请重新扫码!");
                                            return;
                                        }

                                    }
                                if (!string.IsNullOrEmpty(PartCodes[i]))
                                {
                                    HandyControl.Controls.MessageBox.Show("零件条码不符合扫码顺序，请重新扫码!");
                                    DbHelper.Log("零件条码不符合扫码顺序，请重新扫码!");
                                    return;
                                }

                            }
                            else
                            {
                                if (PartCodes.Count == 0)
                                {
                                    HandyControl.Controls.MessageBox.Show("零件条码不符合扫码顺序，请重新扫码!");
                                    DbHelper.Log("零件条码不符合扫码顺序，请重新扫码!");
                                    return;
                                }
                                if (PartCodes.Count <=i)
                                {
                                    HandyControl.Controls.MessageBox.Show("零件条码不符合扫码顺序，请重新扫码!");
                                    DbHelper.Log("零件条码不符合扫码顺序，请重新扫码!");
                                    return;

                                }
                                if (!string.IsNullOrEmpty(PartCodes[i]))
                                {
                                    HandyControl.Controls.MessageBox.Show("零件条码不符合扫码顺序，请重新扫码!");
                                    DbHelper.Log("零件条码不符合扫码顺序，请重新扫码!");
                                    return;
                                }
                            
                            }

                        }
                        if (DbHelper.ContainsPartCode(scanCode))
                        {
                            RepeatCode = scanCode;
                            HandyControl.Controls.MessageBox.Show("零件条码数据库中已包含该条码,请联系管理员解码!");
                            DbHelper.Log("零件条码数据库中已包含该条码,请联系管理员解码!");
                            return;
                        }
                        isMatch = true;
                        proCfg.EnableScans[i].IsScan = true;
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (PartCodes.Count == 0|| PartCodes.Count==i)
                            {
                                PartCodes.Add(scanCode);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(PartCodes[i]))
                                {
                                    PartCodes[i] = scanCode;
                                }
                                else
                                {
                                    PartCodes.Add(scanCode);
                                }
                            }


                        });
                        break; //匹配到一个后跳出for循环
                    }
                }



                string log = isMatch ? $"扫码校验成功:{scanCode}" : $"扫码校验失败:{scanCode}";
                if (!isMatch)
                {
                    HandyControl.Controls.MessageBox.Show(log);
                }
                DbHelper.Log(log);
                //检测是否所有启用码已经扫完
                if (PartCodes.Count() == proCfg.EnableScans.Count() && proCfg.EnableScans.Count() != 0)
                {
                    bool hasEmptyString = PartCodes.Any(String.IsNullOrEmpty);
                    if (!hasEmptyString)
                    {
                        Locator.Instance.Service.ResponseCollection(5);
                        EnablScan = false;
                        if (Fields.Station == "JZ" || Fields.Station == "GP12")
                        {
                            PhotoUrl2 = "";
                            PhotoUrl1 = "";
                        }
                        DbHelper.Log("扫码完成");
                    }
                }
                value = string.Empty;
            }
        }

        private string proModel;
        /// <summary>
        /// 当前生产型号
        /// </summary>
        public string ProModel
        {
            get => proModel;
            set
            {
                if (proModel != value)
                {
                    SetProperty(ref proModel, value);
                }
            }
        }

        private int proStepIndex = -1;
        public int ProStepIndex
        {
            get => proStepIndex;
            set
            {
                if (value < 0) return;
                if (proStepIndex != value)
                {
                    SetProperty(ref proStepIndex, value);
                    ProStep = MsgHelper.StepTipDic[value];
                }
            }
        }

        private string proStep;
        public string ProStep
        {
            get => proStep;
            set => SetProperty(ref proStep, value);
        }

        /// <summary>
        /// 图片1
        /// </summary>
        private string photoUrl1;
        public string PhotoUrl1
        {
            get => photoUrl1;
            set => SetProperty(ref photoUrl1, value);
        }
        /// <summary>
        /// 图片2
        /// </summary>
        private string photoUrl2;
        public string PhotoUrl2
        {
            get => photoUrl2;
            set => SetProperty(ref photoUrl2, value);
        }


        #region 拧紧程序数据结果
         /// <summary>
        /// 角度1
        /// </summary>
        private double angle1;
        public double Angle1
        {
            get => angle1;
            set => SetProperty(ref angle1, value);
        }
        /// <summary>
        /// 角度2
        /// </summary>
        private double angle2;
        public double Angle2
        {
            get => angle2;
            set => SetProperty(ref angle2, value);
        }

        /// <summary>
        /// 角度1结果
        /// </summary>
        private string angle1Result;
        public string Angle1Result
        {
            get => angle1Result;
            set => SetProperty(ref angle1Result, value);
        }
        /// <summary>
        /// 角度2结果
        /// </summary>
        private string angle2Result;
        public string Angle2Result
        {
            get => angle2Result;
            set => SetProperty(ref angle2Result, value);
        }

        /// <summary>
        /// 扭矩1
        /// </summary>
        private double torque1;
        public double Torque1
        {
            get => torque1;
            set => SetProperty(ref torque1, value);
        }
        /// <summary>
        /// 扭矩2
        /// </summary>
        private double torque2;
        public double Torque2
        {
            get => torque2;
            set => SetProperty(ref torque2, value);
        }
        /// <summary>
        /// 扭矩1结果
        /// </summary>
        private string torque1Result;
        public string Torque1Result
        {
            get => torque1Result;
            set => SetProperty(ref torque1Result, value);
        }
        /// <summary>
        /// 扭矩2结果
        /// </summary>
        private string torque2Result;
        public string Torque2Result
        {
            get => torque2Result;
            set => SetProperty(ref torque2Result, value);
        }





        #endregion












        /// <summary>
        /// 是否显示OKNG
        /// </summary>
        private string isShow;
        public string IsShow
        {
            get => isShow;
            set => SetProperty(ref isShow, value);
        }

        public string RepeatCode = string.Empty;
        public string ImageName = string.Empty;
        #region property
        private string curTime;
        private string runTime;
        private bool isConnected;
        private string mes = "本地";
        private string authority = "操作员";
        public ToggleButton QualityBtn = new ToggleButton();
        private ButtonStatus btnCtrStatus = ButtonStatus.NORMAL;
        private ButtonStatus btnMes = ButtonStatus.CHECKED;

        public bool IsConnected
        {
            get => isConnected; set => SetProperty(ref isConnected, value);
        }

        public ButtonStatus BtnMes
        {
            get => btnMes;
            set
            {
                if (value == ButtonStatus.NORMAL)
                {
                    Mes = "本地";
                    ChangeShiftBtn(0, false);
                }
                else if (value == ButtonStatus.CHECKED)
                {
                    Mes = "远程";
                    ChangeShiftBtn(0, true);
                }
                SetProperty(ref btnMes, value);
            }
        }

        public string Authority
        {
            get => authority; set => SetProperty(ref authority, value);
        }
        public ButtonStatus BtnCtrStatus
        {
            get => btnCtrStatus;
            set
            {
                SetProperty(ref btnCtrStatus, value);
            }
        }
        public string Mes
        {
            get => mes; set => SetProperty(ref mes, value);
        }
        public string CurTime
        {
            get => curTime;
            set => SetProperty(ref curTime, value);
        }
        public string RunTime
        {
            get => runTime;
            set => SetProperty(ref runTime, value);
        }

        public string SoftwareVersion => Assembly.GetExecutingAssembly().GetName().Version.ToString();
        #endregion

        #region method

        public HomeViewModel()
        {
            //DbHelper.LogTip("MainPageViewModel");
            //ChangeShiftBtn(0, true);
            //查看是否有多余的Bartender打开
            string processName = "bartend";
            bool isRunning = GlobalFunc.IsProcessRunning(processName);
            if (isRunning)
            {
                //Console.WriteLine($"{processName} is running.");
                GlobalFunc.CloseProcess(processName);
            }
          



        }

        private void ChangeShiftBtn(int bitOffset, bool flag)
        {
            Locator.Instance.Service.LocalRemoteButton(bitOffset, flag);
        }

        private void ChangeMes()
        {
            if (BtnMes == ButtonStatus.NORMAL)
            {
                BtnMes = ButtonStatus.CHECKED;
            }
            else if (BtnMes == ButtonStatus.CHECKED)
            {
                BtnMes = ButtonStatus.NORMAL;
            }

        }

   



        public void PlcMsgChenged(int i, Enums.MsgType type, bool isOn)
        {
            Msg msg = new Msg();
            msg.MsgType = type;
            msg.Index = i + 1;
            string str = isOn ? "添加" : "删除";
            switch (type)
            {
                case Enums.MsgType.Tip:
                    msg.Content = MsgHelper.TipInfoDic[i + 1];
                    DbHelper.LogTip($"{str}:{msg.Content}");
                    break;
                case Enums.MsgType.Warning:
                    msg.Content = MsgHelper.WarningDic[i + 1];
                    DbHelper.LogWarning($"{str}:{msg.Content}");
                    break;
                case Enums.MsgType.Alarm:
                    msg.Content = MsgHelper.AlarmDic[i + 1];
                    DbHelper.LogAlarm($"{str}:{msg.Content}");
                    break;
            }
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (isOn)
                {
                    if (!PlcMsgs.Contains(msg))
                    {
                        PlcMsgs.Add(msg);
                    }
                }
                else
                {
                    var item = PlcMsgs.Where(o => o.Index == msg.Index && o.MsgType == msg.MsgType).FirstOrDefault();
                    if (item != null)
                    {
                        PlcMsgs.Remove(item);
                    }
                }
            });
        }

        
        #endregion

        #region command
        private DelegateCommand changeMesCmd;
        private DelegateCommand<object> setModeCmd;
        public DelegateCommand ChangeMesCmd => changeMesCmd ?? (changeMesCmd = new DelegateCommand(ChangeMes));
        #endregion
    }
}
